/*
 * Tidal - an IDE for Google Wave gadgets.
 * Copyright (C) 2010 Nathan Summers
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.googlecode.tidal.ide.file.jcache;

import com.google.appengine.api.memcache.stdimpl.GCacheFactory;
import com.googlecode.tidal.ide.file.File;
import com.googlecode.tidal.ide.file.FileStore;
import com.googlecode.tidal.ide.file.FileStoreException;

import java.io.Serializable;
import java.util.Collections;
import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheFactory;
import javax.cache.CacheManager;


        

public class JCacheFileStore implements FileStore {
    private static final int FILE_TTL = 5 * 60 * 60;
    private Cache cache;

    public JCacheFileStore() throws FileStoreException {
	try {
	    CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
	    cache = cacheFactory.createCache(Collections.singletonMap(GCacheFactory.EXPIRATION_DELTA, FILE_TTL));
	} catch (CacheException e) {
	    throw new FileStoreException("Could not create cache", e);
	}
    }
    
    /* (non-Javadoc)
     * @see com.googlecode.tidal.ide.file.jcache.FileStore#store(com.googlecode.tidal.ide.file.File)
     */
    public void store(File file) {
	if (!(file instanceof Serializable))
	    file = new SerializableFile(file);
	
	cache.put(file.getFilename(), file);
    }
    
    /* (non-Javadoc)
     * @see com.googlecode.tidal.ide.file.jcache.FileStore#retrieve(java.lang.String)
     */
    public File retrieve(String filename) {
	return (File) cache.get(filename);
    }
}
